package DB;

import Model.Customer;
import Model.Item;
import Model.SalesOrder;
import Model.Status;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

/**
 *
 * @author Tomas
 */
public class SalesOrderManager implements IFSalesOrderManager{

    private Connection con;
    private ItemManager itemManager;
    private CustomerManager customerManager;
    private StatusManager statusManager;

    public SalesOrderManager(){
        con = DBConnector.getInstance().getDBConnection();
        itemManager = new ItemManager();
        customerManager = new CustomerManager();
        statusManager = new StatusManager();
    }
    public SalesOrder getSalesOrder(int orderId, boolean retreiveAssociations) throws IllegalArgumentException {
        SalesOrder result= new SalesOrder();
        String param = ""+orderId;
        result = singleWhere("salesOrderid = ?",new String[]{param}, retreiveAssociations);
        return result;
    }

    public void createSalesOrder(SalesOrder order, boolean updateAssociations) {
       String query = "INSERT INTO SalesOrder(date, totalPrice, deliveryDate,"
               + "customerId, discount, deliveryFee, statusId) VALUES(?,?,?,"
               + "?, ?, ?, ?)";
        try {
            PreparedStatement stmt = con.prepareStatement(query);
            stmt.setDate(1, new Date(order.getDate().getTime()));
            stmt.setFloat(2, order.getTotalPrice());
            stmt.setDate(3, new Date(order.getDeliveryDate().getTime()));
            stmt.setInt(4, order.getCustomer().getCustomerId());
            stmt.setInt(5, order.getDiscount());
            stmt.setFloat(6, order.getDeliveryFee());
            stmt.setInt(7, order.getStatus().getStatusId());
            System.out.println("Status ID: "+order.getStatus().getStatusId());
            stmt.setQueryTimeout(5);
            if(stmt.executeUpdate() == 0){
                throw new IllegalArgumentException("Creation of sales order failed");
            }else{
                ArrayList<Item> items = order.getItems();
                int maxID = getMaxID();
                for(Item z: items){
                    itemManager.assignItemToOrder(z, maxID);
                }
            }
            stmt.close();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

    }

    public void updateSalesOrder(SalesOrder order, boolean updateAssociations) {
         String query = "UPDATE SalesOrder set date = ?, totalPrice = ?, deliveryDate = ?,"
               + "customerId = ?, discount = ?, deliveryFee = ?, statusId = ? WHERE salesOrderId = ?";
        try {
            PreparedStatement stmt = con.prepareStatement(query);
            stmt.setDate(1, new Date(order.getDate().getTime()));
            stmt.setFloat(2, order.getTotalPrice());
            stmt.setDate(3, new Date(order.getDeliveryDate().getTime()));
            stmt.setInt(4, order.getCustomer().getCustomerId());
            stmt.setInt(5, order.getDiscount());
            stmt.setFloat(6, order.getDeliveryFee());
            stmt.setInt(7, order.getStatus().getStatusId());
            stmt.setInt(8, order.getSalesOrderId());
            stmt.setQueryTimeout(5);
            if(stmt.executeUpdate() == 0){
                throw new IllegalArgumentException("Creation of sales order failed");
            }
            stmt.close();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
    private SalesOrder singleWhere(String whereC, String[] params, boolean assoc){
        ResultSet results;
        SalesOrder salesOrderObject = null;

        String query = buildQuery(whereC);
        try {
            PreparedStatement stmt = con.prepareStatement(query);
            for(int a = 0; a<params.length;a++){
              stmt.setString(a+1, params[a]);
            }
            stmt.setQueryTimeout(5);
            results = stmt.executeQuery();
            if(results.next()){
                salesOrderObject = buildSalesOrder(results);
                stmt.close();
                if(assoc){
                    ArrayList<Item> itemList = itemManager.getItems(salesOrderObject.getSalesOrderId(), assoc);
                    salesOrderObject.setItems(itemList);

                    Customer cust = customerManager.getCustomer(salesOrderObject.getCustomer().getCustomerId(),false);
                    salesOrderObject.setCustomer(cust);

                    Status status = statusManager.getStatusByID(salesOrderObject.getStatus().getStatusId());
                    salesOrderObject.setStatus(status);
                }else{
                   salesOrderObject.setCustomer(null);
                   salesOrderObject.setStatus(null);
                }
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        if(salesOrderObject == null){
            throw new IllegalArgumentException("SalesOrder not found");
        }
        return salesOrderObject;
    }
    private String buildQuery(String whereC){
        String query = "SELECT * FROM SalesOrder";
        if(!whereC.isEmpty()){
            query = query+" WHERE "+whereC;
        }
        return query;
    }
    private SalesOrder buildSalesOrder(ResultSet resSet){
        SalesOrder order = new SalesOrder();
        try {
            order.setSalesOrderId(resSet.getInt(1));
            order.setDate(resSet.getDate(2));
            order.setItems(null);
            order.setTotalPrice(resSet.getFloat(3));
            order.setDeliveryDate(resSet.getDate(4));
            order.setCustomer(new Customer(resSet.getInt(5)));
            order.setDiscount(resSet.getInt(6));
            order.setDeliveryFee(resSet.getFloat(7));
            order.setStatus(new Status(resSet.getInt(8)));
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        return order;
    }
    private int getMaxID(){
        int id = 0;
        String query = "SELECT MAX(salesOrderId) AS maksi FROM SalesOrder";
        ResultSet rs;
        Statement stmt;
        try {
            stmt = con.createStatement();
            stmt.setQueryTimeout(5);
            rs = stmt.executeQuery(query);
            if(rs.next()){
              id = rs.getInt(1);
            }
            stmt.close();
        } catch (SQLException ex) {
         id = 0;
        }
        
        return id;
    }
}
